<?php

namespace app\uniapp\controller;

use app\common\controller\CommonController;
use app\common\exception\MiException;
use app\common\service\CommonNoticeTplService;
use app\common\service\CommonSiteConfigService;
use app\common\service\sms\SmsService;
use app\model\NoticeTpl;
use app\service\wx\WxMpService;
use app\uniapp\service\UniAuthService;
use thans\jwt\facade\JWTAuth;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Request;
use think\response\Json;

class PublicController extends CommonController
{
    /**
     * @var int|mixed
     */
    private int $siteId;

    /**
     * @throws MiException
     */
    public function __construct()
    {
        $this->siteId = UniAuthService::instance()->getSiteId();
    }

    /**
     * 发送短信验证码
     * @return Json
     * @throws MiException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function sendVerifySms(): Json
    {

        $mobile = $this->param('mobile');
        if (!$mobile) return jsonError("手机号错误");
        $type = $this->param('type', '');
        if (!$type) return jsonError("缺少验证码类型");

        $smsSer = SmsService::instance($this->siteId);
        // 生成6位随机数，并存入session，有效期为3分钟
        $code = rand(100000,999999);
        Cache::set('verify'.$type.$mobile, $code, 180);

        $tpl = CommonNoticeTplService::instance()->getSmsCode($this->siteId);
        // 读取模板，并替换模板中的{$code}
        $content = str_replace('{$code}', $code, $tpl->sms_text);

        $smsSer->send($mobile, $content);
        
        return jsonSuccess();
    }

    /**
     * 验证短信验证码
     * @return Json
     */
    public function validateVerifySms(): Json
    {

        $mobile = $this->param('mobile');
        $code = $this->param('code');
        $type = $this->param('type');
        if (!$mobile) return jsonError('手机号错误');
        if (!$type) return jsonError('验证码类型错误');

        // 验证短信验证码
        if (SmsService::instance($this->siteId)->validateCode($code, $type, $mobile)){
            return jsonSuccess();
        }else{
            return jsonError();
        }

    }

    /**
     * 获取openid
     * @throws \Exception
     */
    public function getWxMpSession(Request $request): Json
    {
        $code = $request->param('code', '');
        $config = CommonSiteConfigService::instance()->getConfigValue(UniAuthService::instance()->getSiteId(), CommonSiteConfigService::WX_MP);
        $session = WxMpService::instance($config)->getWxMpSession($code);
        return jsonSuccess([
           'openid' => $session['openid']
        ]);
    }

    /**
     * 刷新令牌
     */
    public function refreshToken(): \think\response\Json
    {
        try {
            // 尝试刷新token
            $token = JWTAuth::refresh();
        }catch (\Exception $e){
            return jsonError("刷新令牌失败");
        }

        return jsonSuccess([
            'token' => $token
        ]);
    }

}
